package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"atomgit.com/openlinksaas/proto-gen-go.git/net_proxy_api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func getProxyConn(proxyAddr string) (*grpc.ClientConn, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	return grpc.DialContext(ctx, proxyAddr, grpc.WithInitialConnWindowSize(1<<30),
		grpc.WithInitialWindowSize(1<<30), grpc.WithTransportCredentials(insecure.NewCredentials()))
}

func main() {
	if len(os.Args) != 4 {
		fmt.Printf("Usage:%s [proxy addr] [tunnel Id] [port]\n", os.Args[0])
		return
	}
	proxyAddr := os.Args[1]
	tunnelId := os.Args[2]
	portStr := os.Args[3]

	conn, err := getProxyConn(proxyAddr)
	if err != nil {
		fmt.Println(err)
		return
	}
	client := net_proxy_api.NewNetProxyApiClient(conn)

	addr := fmt.Sprintf("127.0.0.1:%s", portStr)
	err = listenTcp(tunnelId, addr, client)
	if err != nil {
		fmt.Println(err)
		return
	}
}
